/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "memorymap.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <stdlib.h>
#include "arm_math.h"
extern uint16_t testing_signal[RLS_N];

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
enum DEVICE_STATUS {
  STATUS_WAITING,
  STATUS_BASIC,
  STATUS_ADVANCED_1,
  STATUS_ADVANCED_2,
};
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) uint16_t adc_buffer[BUFFER_SIZE*2]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) uint16_t dac_buffer[BUFFER_SIZE*2]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t dsp_buffer[BUFFER_SIZE]);

volatile uint8_t adc_buffer_flag = 0;
volatile float DeviceOutputVpp = 0;
volatile float DeviceOutputFreq = 1000;
volatile float CircuitOutputVpp = 2.0;

float64_t theta_est[5] = {0};
float64_t RLS_P[5 * 5] = { 
    5,0,0,0,0,
    0,5,0,0,0,
    0,0,5,0,0,
    0,0,0,5,0,
    0,0,0,0,5
}; // Initial covariance matrix
ALIGN_32BYTES(__attribute__((section(".AXI_RAM")))float64_t RLS_Output[RLS_N]); // Output signal

arm_matrix_instance_f64 matP = {5, 5, RLS_P}; // Initialize the matrix instance with the P matrix
arm_matrix_instance_f64 matTheta = {5, 1, theta_est}; // Initialize the matrix instance with the theta_est array

enum DEVICE_STATUS DeviceStatus = STATUS_ADVANCED_1;
arm_biquad_casd_df1_inst_f32 iir_filter;
float32_t coeffs[5];
uint16_t counter = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
static void MPU_Config(void);
/* USER CODE BEGIN PFP */
extern float Voltage_Calculate(float DeviceOutputFreq, float CircuitOutputVpp);
extern void Data_Process(uint16_t* src, uint16_t* dst, uint32_t length);

void RLS_Update(int k);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MPU Configuration--------------------------------------------------------*/
  MPU_Config();

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* Configure the peripherals common clocks */
  PeriphCommonClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC1_Init();
  MX_TIM2_Init();
  MX_TIM6_Init();
  MX_USART1_UART_Init();
  MX_DAC1_Init();
  /* USER CODE BEGIN 2 */
	
	HAL_DAC_Start(&hdac1,DAC_CHANNEL_1);
	HAL_DAC_SetValue(&hdac1,DAC_CHANNEL_1,DAC_ALIGN_12B_R,2048);
	HAL_Delay(5000);
  DeviceStatus = STATUS_ADVANCED_1; // Set initial status to advanced mode 1

	HAL_TIM_Base_Init(&htim6);
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		switch(DeviceStatus)
    {
      case STATUS_WAITING:


        break;
      case STATUS_BASIC:
      //count DeviceOutputVpp with H(s),DeviceOutputFreq and CircuitOutputVpp
        DeviceOutputVpp = (DeviceOutputFreq, CircuitOutputVpp);  
        //set DDS output with H(s)


        DeviceStatus = STATUS_WAITING;
        break;
      case STATUS_ADVANCED_1:

        // Send and receive testing signal
				HAL_DAC_Stop(&hdac1, DAC_CHANNEL_1);
				adc_buffer_flag = 0;
        HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buffer, RLS_N);
        HAL_DAC_Start_DMA(&hdac1,DAC_CHANNEL_1,(uint32_t*)testing_signal,RLS_N,DAC_ALIGN_12B_R);
        HAL_TIM_Base_Start(&htim2);

        // Receive Data from ADC
	      while(1 != adc_buffer_flag)
					;
        for(uint16_t i=0;i<RLS_N/2;i++) {
					RLS_Output[i]= (float64_t)adc_buffer[i] *3.3f / 65536.0f;
				}
				adc_buffer_flag = 0;

	      while(2 != adc_buffer_flag)
					;
        adc_buffer_flag = 0;
	      HAL_TIM_Base_Stop(&htim2);
	      HAL_ADC_Stop_DMA(&hadc1);
				HAL_DAC_Stop_DMA(&hdac1,DAC_CHANNEL_1);
        for(uint16_t i=RLS_N/2;i<RLS_N;i++) {
					RLS_Output[i]= (float64_t)adc_buffer[i] *3.3f / 65536.0f;
				}

        // deal with DC offset
        float64_t ADC_Offset_Voltage;
        arm_mean_f64(RLS_Output, RLS_N, (float64_t*) &ADC_Offset_Voltage); // Calculate the Offset Voltage
        arm_offset_f64(RLS_Output, -ADC_Offset_Voltage, RLS_Output, RLS_N); // Subtract the Offset Voltage
        
        // RLS主循环
        for(int k=2; k<RLS_N; k++) {
            RLS_Update(k);
        
            // 每100次迭代输出结果（通过串口）
            if(k % 100 == 0) {
                printf("Iter %d: a1=%.2e, a2=%.2e, b0=%.2e, b1=%.2e, b2=%.2e\n", k, theta_est[0], theta_est[1], theta_est[2], theta_est[3], theta_est[4]);
            }
        }
    
        // 最终结果输出
        printf("Final Parameters:\n");
        printf("a1: %.2e\n", theta_est[0]);
        printf("a2: %.2e\n", theta_est[1]);
        printf("b0: %.2e\n", theta_est[2]);
        printf("b1: %.2e\n", theta_est[3]);
        printf("b2: %.2e\n", theta_est[4]);

        //display type of circuit
        // DeviceStatus = STATUS_WAITING;
        DeviceStatus = STATUS_ADVANCED_2; // Debugging
        break;
				
      case STATUS_ADVANCED_2:

        // Set up IIR filter coefficients
        coeffs[0] = theta_est[2]; // b0
        coeffs[1] = theta_est[3]; // b1
        coeffs[2] = theta_est[4]; // b2
        coeffs[3] = -theta_est[0]; // a1
        coeffs[4] = -theta_est[1]; // a2
        
        arm_biquad_cascade_df1_init_f32(&iir_filter, 1, coeffs, dsp_buffer);

        //getting data from ADC and displaying data with DDS (imitate the circuit, this case is a loop)
        HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buffer, BUFFER_SIZE*2);
	      HAL_DAC_Start_DMA(&hdac1,DAC_CHANNEL_1,(uint32_t*)dac_buffer,BUFFER_SIZE*2,DAC_ALIGN_12B_R);
	      HAL_TIM_Base_Start(&htim2);

        while(DeviceStatus == STATUS_ADVANCED_2)
        {
          if(adc_buffer_flag == 1) 
          {
            Data_Process(adc_buffer, dac_buffer, BUFFER_SIZE);
            adc_buffer_flag = 0;
          }
          else if(adc_buffer_flag == 2)
          {
            Data_Process(adc_buffer + BUFFER_SIZE, dac_buffer + BUFFER_SIZE, BUFFER_SIZE);
            adc_buffer_flag = 0;
          }
        }
        DeviceStatus = STATUS_WAITING;
        break;
    }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 2;
  RCC_OscInitStruct.PLL.PLLN = 44;
  RCC_OscInitStruct.PLL.PLLP = 1;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }

  /** Enables the Clock Security System
  */
  HAL_RCC_EnableCSS();
}

/**
  * @brief Peripherals Common Clock Configuration
  * @retval None
  */
void PeriphCommonClock_Config(void)
{
  RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};

  /** Initializes the peripherals clock
  */
  PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_ADC|RCC_PERIPHCLK_USART1;
  PeriphClkInitStruct.PLL2.PLL2M = 2;
  PeriphClkInitStruct.PLL2.PLL2N = 48;
  PeriphClkInitStruct.PLL2.PLL2P = 4;
  PeriphClkInitStruct.PLL2.PLL2Q = 6;
  PeriphClkInitStruct.PLL2.PLL2R = 2;
  PeriphClkInitStruct.PLL2.PLL2RGE = RCC_PLL2VCIRANGE_3;
  PeriphClkInitStruct.PLL2.PLL2VCOSEL = RCC_PLL2VCOWIDE;
  PeriphClkInitStruct.PLL2.PLL2FRACN = 0;
  PeriphClkInitStruct.Usart16ClockSelection = RCC_USART16910CLKSOURCE_PLL2;
  PeriphClkInitStruct.AdcClockSelection = RCC_ADCCLKSOURCE_PLL2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void RLS_Update(int k) {
    float64_t RLS_Input[3] = 
      {testing_signal[k]*3.3f / 4096.0f, (float)testing_signal[k-1] *3.3f /4096.0f, (float)testing_signal[k-2]*3.3f /4096.0f};
    
    // phi = [y[k-1], y[k-2], x[k], x[k-1], x[k-2]]
    float64_t phi_data[5] = {RLS_Output[k-1], RLS_Output[k-2], RLS_Input[0], RLS_Input[1], RLS_Input[2]};
    arm_matrix_instance_f64 phi = {5, 1, phi_data}; // Initialize the matrix instance with phi
    
    // 1. 计算增益K = P * φ / (λ + φᵀPφ)
    arm_matrix_instance_f64 Pphi = {5, 1, NULL};
    arm_mat_mult_f64(&matP, &phi, &Pphi); // P * φ

    arm_matrix_instance_f64 phiT = {1, 5, NULL};
    arm_mat_trans_f64(&phi, &phiT); // φᵀ

		
    arm_matrix_instance_f64 phiT_Pphi_matrix = {1, 1, NULL};
    arm_mat_mult_f64(&phiT, &Pphi, &phiT_Pphi_matrix); // φᵀPφ
		float64_t phiT_Pphi = phiT_Pphi_matrix.pData[0];
    
    float64_t denom = LAMBDA + phiT_Pphi;
    float64_t K_data[5];
    arm_scale_f64(&Pphi.pData[0], 1/denom, K_data, 5); // K = Pphi / denom

    // 2. 预测输出 y_pred = φᵀ * θ
    float64_t y_pred;
    arm_dot_prod_f64(&phiT.pData[0], theta_est, 5, &y_pred);

    // 3. 参数更新 θ = θ + K*(y[k] - y_pred)
    float64_t error = RLS_Output[k] - y_pred;
    float64_t K_error[5];
    arm_scale_f64(K_data, error, K_error, 5);
    arm_add_f64(theta_est, K_error, theta_est, 5);

    // 4. 协方差更新 P = (P - K*φᵀP) / λ
    float64_t K_phiT[5 * 5];
    arm_mat_mult_f64(&(arm_matrix_instance_f64){5,1,K_data}, 
                     &(arm_matrix_instance_f64){1,5,phi_data}, 
                     &(arm_matrix_instance_f64){5,5,K_phiT}); // K*φᵀ
    
    float64_t P_temp[25];
    arm_mat_mult_f64(&(arm_matrix_instance_f64){5,5,K_phiT}, 
                     &matP, 
                     &(arm_matrix_instance_f64){5,5,P_temp}); // (Kφᵀ)P
    
    arm_sub_f64(RLS_P, P_temp, RLS_P, 25); // P - KφᵀP
    arm_scale_f64(RLS_P, 1/LAMBDA, RLS_P, 25); // 除以λ
}

void Data_Process(uint16_t* src, uint16_t* dst, uint32_t length)
{
	for(int i=0;i<length;i++)
  {
    dsp_buffer[i] = src[i] * 3.3f / 65536;
  }

  arm_biquad_cascade_df1_f32(&iir_filter, dsp_buffer, dsp_buffer,BUFFER_SIZE);

  for(int i=0;i<length;i++)
  {
    dst[i] = dsp_buffer[i] / 3.3f * 4096;
  }
}
/* USER CODE END 4 */

 /* MPU Configuration */

void MPU_Config(void)
{
  MPU_Region_InitTypeDef MPU_InitStruct = {0};

  /* Disables the MPU */
  HAL_MPU_Disable();

  /** Initializes and configures the Region and the memory to be protected
  */
  MPU_InitStruct.Enable = MPU_REGION_ENABLE;
  MPU_InitStruct.Number = MPU_REGION_NUMBER0;
  MPU_InitStruct.BaseAddress = 0x0;
  MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
  MPU_InitStruct.SubRegionDisable = 0x87;
  MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
  MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
  MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
  MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;
  MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
  MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;

  HAL_MPU_ConfigRegion(&MPU_InitStruct);
  /* Enables the MPU */
  HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);

}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
